
; (function(global){

    if(!global.applicationCache){
        global.location.href="http://hw.hackerwand.com/nohtml5.html";
    }
    global.HW = {};
    HW.Document = {}; 
    HW.Document.document = $(document);
    HW.Document.body = $('body').eq(0);
    HW.Widget = {};
    HW.Widget.upload = {
        Create: function(){}
    }

    HW.Pop = {}; 

    HW.Pop.message = {
        Create: function() {}, 
        Close: function() {} 
    }; 

    HW.Pop.progress = {
        Create: function() {}
    };

    /**
     * 文件上传控件
     * _W:{}
     * _W.target:jq selector
     * _W.uploadText:string 上传按钮文字
     * _W.mult:Boolean 是否为多文件上传 默认为false
     * _W.accept:[] 允许上传的文件类型 ['png','jpg','jpeg']
     * _W.inputName:string 文件上传参数名 默认为HW_upload_input
     * _W.maxSize:int 允许上传的文件大小 单位为kb 默认为 4096
     * _W.fileCheck:function 检查文件是否允许上传 允许上传则返回true 不允许则返回错误提示
     * _W.viewSize:[] 设置图片预览框宽高 默认为400，300
     * _W.viewImageWidth:int 设置预览图片宽度 默认为80
     * _W.isImage:Boolean 设置支持图片上传 默认为true
     * _W.done:function 上传完成回调函数
     */

     HW.Widget.upload.Create = function(_W) {
        if (typeof _W === 'undefined' || typeof _W.target === 'undefined' || typeof _W.url === 'undefined' || $.trim(_W.url) == '')
            return null;
        this.upload = $(_W.target).eq(0);

        if (this.upload.length < 1)
            return;
        _W.uploadText = typeof _W.uploadText === 'undefined' ? ($.trim(this.upload.text()) == '' ? '请选择要上传的文件' : this.upload.text()) : _W.uploadText;
        _W.mult = typeof _W.mult !== 'boolean' ? false : _W.mult;
        _W.accept = typeof _W.accept === 'undefined' ? ['png', 'jpg', 'jpeg'] : _W.accept;
        _W.inputName = typeof _W.inputName === 'undefined' ? 'HW_upload_files' : _W.inputName;
        _W.FileReader = typeof FileReader === 'function' ? true : false;
        _W.FormData = typeof FormData === 'function' ? true : false;
        _W.maxSize = typeof _W.maxSize !== 'number' ? 4096 : _W.maxSize;
        _W.fileCheck = typeof _W.fileCheck !== 'function' ? null : _W.fileCheck;
        _W.viewSize = typeof _W.viewSize === 'undefined' ? [400, 300] : _W.viewSize;
        _W.viewImageWidth = typeof _W.viewImageWidth !== 'number' ? 80 : _W.viewImageWidth;
        _W.isImage = typeof _W.isImage !== 'boolean' ? true : _W.isImage;
        _W.timeout = typeof _W.timeout !== 'number' ? 20 : _W.timeout;
        _W.done = typeof _W.done !== 'function' ? HW.NULLF : _W.done;
        this._W = _W;

        //允许上传参数
        this.setAccept = function(accept, input) {
            input = this.fileInput || input;
            if (typeof accept === 'undefined')
                accept = ['png', 'jpg', 'jpeg'];
            input.attr('accept','');
            for (var i = 0; i < accept.length; i++)
                accept[i] = '.' + accept[i];
            accept = accept.join(',');
            input.attr('accept', accept);
        }

        this._initUpload = function() {
            this.upload.html('');
            this.upload.append($('<span class="HW_upload_text">' + _W.uploadText + '</span>'));
            this.fileInput = $('<input class="HW_upload_form" type="file"/ style="display: none">');
            this.setAccept(_W.accept);
            this.fileInput.attr({
                multiple: _W.mult,
                id: _W.inputName,
                name: _W.inputName
            });

            this.uploadFiles = [];
            this.fileInput.change(this.ActionFunction(this._fileChange));
        }

        this._readyUpload = function() {
            this.upload.children('span.HW_upload_text').remove();
            this.upload.append($('<div class="HW_start_but">开始上传</div>'));
            this.upload.append($('<div class="HW_change_but">重新选择</div>'));
        }

        this._fileCheck = function(file) {
            if (_W.fileCheck !== null)
                return _W.fileCheck(file);
            if (this._W.accept.join('').indexOf(file.type.split('/')[1]) < 0)
                return  alert('不允许上传的文件类型');
            if (this._W.maxSize * 1024 < file.size)
                return alert('只允许上传小于' + this._W.maxSize + 'kb的文件');
            return true;
        }

        this.ActionFunction = function(fun) {
            var x = this;
            return function(event) {
                var target = $(event.target || event.srcElement);
                fun.call(x, event, target);
            }
        }

        this._fileChange = function(event, input) {
            this.uploadFiles = [];
            var checkResult = '';
            for (var i = 0; i < input[0].files.length; i++) {
                if ((checkResult = this._fileCheck(input[0].files[i])) !== true) {
                    break;
                }
                this.uploadFiles[i] = input[0].files[i];
            }
            if (checkResult !== true) {
                this.uploadFiles = [];
                HW.Pop.message.Create({
                    text: checkResult,
                    fun: (function(x) {
                        return function() {
                            x.openFileDialog();
                        }
                    })(this)
                });
                return checkResult;
            }
            this._readyUpload();

        }

        this._initUpload();

        HW.Document.body.append(this.fileInput);

        //上传选中的文件
        this.send = function() {
            var that = this;
            
            if (this.uploadFiles.length < 1) {
                alert('请先选择要上传的文件')
                HW.Pop.message.Create({
                    text: '请先选择要上传的文件',
                    butText: '选择',
                    fun: (function(x) {
                        return function() {
                            x.openFileDialog();
                            x._initUpload();
                        }
                    })(this)
                })
                return;
            }

            //获取文件扩展名
            var getFileExtension = function (filename) {
                var tempArr = filename.split(".");
                var ext;
                if (tempArr.length === 1 || (tempArr[0] === "" && tempArr.length === 2)) {
                    ext = "";
                } else {
                    ext = tempArr.pop().toLowerCase(); 
                }
                return ext;
            };

            var fileName = null;
            if (opt.key) { 
                fileName = opt.key;
            }else{
                //非覆盖上传，重新获取文件名
                $.ajax({
                    url: opt.apiHost + "/api/qiniu/qiniutoken/CreateFileName?category=" + opt.category,
                    async: false,
                    success: function (data) {
                        var ext = getFileExtension(that.uploadFiles[0].name)
                        fileName = data.result + "." + ext;
                    }
                });
            }

            //是否支持文件上传
            if (this._W.FormData) {

                var files = new FormData();
                files.append('token', _W.uptoken)
                files.append('file', this.uploadFiles[0]);
                files.append('key', fileName);

                $.ajax({
                    url: this._W.url,
                    type: 'POST',
                    data: files,
                    contentType: false,
                    processData: false,
                    timeout: 1000 * 60 * this._W.timeout,
                    xhr: xhrOnProgress(function(e) {
                        HW.Pop.progress.Create(100 * (e.loaded / e.total))
                        _W.onProgress(100 * (e.loaded / e.total))
                    })
                })
                .done((function(x) {
                    return function(data) {
                        x._W.done(data);
                        xhrOnProgress.onprogress = null;
                    }
                })(this))
                .fail(function(data) {
                    alert('上传失败,请稍后重试')
                    HW.Pop.message.Create({
                        text: '上传失败,请稍后重试'
                    });
                });
            } else {
                alert('浏览器版本过低，无法上传')
                HW.Pop.message.Create({
                    text: '浏览器版本过低，无法上传'
                });
            }
        }

            //打开文件选择窗口
            this.openFileDialog = function() {
                this.fileInput.click();
            }

            this.upload.click(this.ActionFunction(function(event, target) {
                if (target.hasClass('HW_upload_text')) {
                    this.fileInput.click();
                } else if (target.hasClass('HW_start_but')) {
                    this.send();
                } else if (target.hasClass('HW_change_but')) {
                    this._initUpload();
                    this.openFileDialog();
                }
            }));

            var xhrOnProgress = function(fun) {
                xhrOnProgress.onprogress = fun; //绑定监听函数
                return function() {
                    var xhr = $.ajaxSettings.xhr();
                    if (xhrOnProgress.onprogress == null || typeof xhrOnProgress.onprogress === 'undefined')
                        return xhr;
                    if (xhrOnProgress.onprogress && xhr.upload) {
                        xhr.upload.onprogress = xhrOnProgress.onprogress;
                    }
                    return xhr;
                }
            };
        }

        var QiniuNew = HW.Widget.upload.Create;
        global.QiniuNew = QiniuNew;


    })(window)



